import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import ThemeToggle from '../components/ui/ThemeToggle';
import VotableDrawing from '../components/VotableDrawing';
import { getPublicDrawings } from '../utils/drawingApi';
import type { Drawing } from '../types/drawing';

const WIDTH = 1000;
const HEIGHT = 600;
const WATERLINE_Y = 320; // 水面高度（y 越大越靠下）

const HomePage: React.FC = () => {
  const [publicDrawings, setPublicDrawings] = useState<Drawing[]>([]);
  const [showTutorial, setShowTutorial] = useState(false);
  const [showUserMenu, setShowUserMenu] = useState(false);
  const [loading, setLoading] = useState(true);
  const { user, logout } = useAuth();
  
  // 获取公开的画作
  useEffect(() => {
    const fetchPublicDrawings = async () => {
      try {
        setLoading(true);
        const response = await getPublicDrawings(1, 50); // 增加获取数量
        console.log('获取到的公开作品:', response);
        
        // 直接使用API返回的数据，API已经过滤了isPublic=true的作品
        if (response.data && Array.isArray(response.data)) {
          setPublicDrawings(response.data);
        } else {
          console.error('获取到的公开作品数据格式不正确:', response);
          setPublicDrawings([]);
        }
      } catch (error) {
        console.error('Failed to load public drawings:', error);
        setPublicDrawings([]);
      } finally {
        setLoading(false);
      }
    };
    
    fetchPublicDrawings();
  }, []);

  // 点击外部关闭下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Element;
      if (!target.closest('.user-menu-container')) {
        setShowUserMenu(false);
      }
    };

    if (showUserMenu) {
      document.addEventListener('click', handleClickOutside);
      return () => document.removeEventListener('click', handleClickOutside);
    }
  }, [showUserMenu]);
  
  // 生成水面波浪路径
  const wavePathD = React.useMemo(() => {
    const segments: string[] = [];
    segments.push(`M 0,${WATERLINE_Y}`);
    for (let i = 0; i < 10; i++) {
      const x0 = i * 100;
      segments.push(
        `C ${x0 + 50},${WATERLINE_Y + 6} ${x0 + 50},${WATERLINE_Y - 6} ${x0 + 100},${WATERLINE_Y}`
      );
    }
    return segments.join(' ');
  }, []);

  // 夜空星星（仅作为视觉点缀）
  const stars = React.useMemo(() => {
    return Array.from({ length: 40 }).map((_, i) => ({
      id: i,
      left: Math.random() * 100, // vw
      top: Math.random() * 45, // 仅天空上半区
      size: Math.random() * 2 + 1,
      delay: Math.random() * 2,
    }));
  }, []);

  return (
    <div className="homepage sea-sky-background">
      {/* Header */}
      <header className="fixed top-0 left-0 right-0 z-40 bg-transparent border-none shadow-none">
        <div className="container mx-auto px-4 py-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <img src="/logo.svg" alt="海天摸鱼" className="w-8 h-8" />
            <h1 className="text-xl font-bold text-base-content site-title">海天摸鱼olllo.cc</h1>
            </div>
            <div className="flex items-center gap-4">
              <ThemeToggle />
              {user ? (
                <div className="dropdown dropdown-end">
                  <div tabIndex={0} role="button" className="btn btn-ghost">
                    {user.username}
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                    </svg>
                  </div>
                  <ul tabIndex={0} className="dropdown-content menu bg-base-100 rounded-box z-[9999] w-52 p-2 shadow">
                    <li><Link to="/change-password">修改密码</Link></li>
                    <li><button onClick={logout}>登出</button></li>
                  </ul>
                </div>
              ) : (
                <Link to="/login" className="btn btn-primary">开始</Link>
              )}
            </div>
          </div>
        </div>
      </header>

      {/* 星空（仅深色主题显示，样式在 CSS 控制可见性） */}
      <div className="star-layer">
        {stars.map((s) => (
          <span
            key={s.id}
            className="star"
            style={{
              left: `${s.left}vw`,
              top: `${s.top}vh`,
              width: `${s.size}px`,
              height: `${s.size}px`,
              animationDelay: `${s.delay}s`,
            }}
          />
        ))}
      </div>

      <div className="sea relative z-0">
        <svg width="100%" height="100%" viewBox={`0 0 ${WIDTH} ${HEIGHT}`} preserveAspectRatio="none" className="sea-svg">
        <defs>
          <linearGradient id="skyGrad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="var(--sky-top)" />
            <stop offset="100%" stopColor="var(--sky-bottom)" />
          </linearGradient>
          <linearGradient id="seaGrad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="var(--sea-top)" />
            <stop offset="100%" stopColor="var(--sea-bottom)" />
          </linearGradient>
        </defs>

        {/* 天空区域 */}
        <rect x="0" y="0" width={WIDTH} height={WATERLINE_Y} fill="url(#skyGrad)" />

        {/* 海水区域（仅水面以下）*/}
        <rect x="0" y={WATERLINE_Y} width={WIDTH} height={HEIGHT - WATERLINE_Y} fill="url(#seaGrad)" opacity="0.95" />

        {/* 水面波纹 */}
        <path d={wavePathD} stroke="var(--wave-color)" strokeWidth="2" fill="none" />

        {/* 移除默认的船 */}
        {/* 公开的可投票绘画展示 */}
        {loading ? (
          <text x={WIDTH/2} y={HEIGHT/2} textAnchor="middle" fill="var(--text-color)" fontSize="16">
            加载中...
          </text>
        ) : publicDrawings.length === 0 ? (
          <text x={WIDTH/2} y={HEIGHT/2} textAnchor="middle" fill="var(--text-color)" fontSize="16">
            暂无公开作品
          </text>
        ) : (
          publicDrawings.map((item, idx) => {
            // 根据类型决定位置
            let x, y;
            
            if (item.drawingType === 'bird') {
              // 鸟在天空
              x = (idx + 1) * (WIDTH / (publicDrawings.length + 1));
              y = WATERLINE_Y - 100 - ((idx % 3) * 20);
            } else if (item.drawingType === 'fish') {
              // 鱼在水下
              x = (idx + 1) * (WIDTH / (publicDrawings.length + 1));
              y = WATERLINE_Y + 100 + ((idx % 3) * 20);
            } else {
              // 船在水面
              x = (idx + 1) * (WIDTH / (publicDrawings.length + 1));
              y = WATERLINE_Y + 10;
            }
            
            const username = (item.user && typeof item.user === 'object' && !Array.isArray(item.user)) 
                            ? (item.user.username || item.user.email?.split('@')[0] || '匿名用户')
                            : '匿名用户';
            
            return (
              <VotableDrawing
                key={item.id}
                id={item.id}
                dataUrl={item.imageData}
                type={item.drawingType}
                username={username}
                x={x}
                y={y}
              />
            );
          })
        )}
      </svg>
      </div>

      <div className="fixed bottom-8 left-1/2 transform -translate-x-1/2 flex gap-4 z-30">
        <Link to="/draw" className="btn btn-primary btn-lg shadow-lg floaty">
          <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
          </svg>
          开始绘画
        </Link>
        <Link to="/saved" className="btn btn-secondary btn-lg shadow-lg floaty">
          <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
          </svg>
          我的画作
        </Link>
        <Link to="/leaderboard" className="btn btn-accent btn-lg shadow-lg floaty">
          <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
          </svg>
          排行榜
        </Link>
        <button 
          onClick={() => setShowTutorial(true)} 
          className="btn btn-info btn-lg shadow-lg floaty"
          title="查看教程"
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        </button>
      </div>

      {showTutorial && (
        <div className="modal modal-open z-[10000]">
          <div className="modal-box">
            <h3 className="font-bold text-lg mb-4">使用指南</h3>
            <div className="space-y-3">
              <p className="flex items-center gap-2">
                <span className="text-2xl">🎨</span>
                点击"开始绘画"进入绘画页面
              </p>
              <p className="flex items-center gap-2">
                <span className="text-2xl">🤖</span>
                使用AI识别功能自动识别你的绘画
              </p>
              <p className="flex items-center gap-2">
                <span className="text-2xl">💾</span>
                保存后你的作品会在这里展示
              </p>
            </div>
            <div className="modal-action">
              <button onClick={() => setShowTutorial(false)} className="btn btn-primary">关闭</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default HomePage;

